package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Resource
    private UserMapper userMapper;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //生成验证码
        String code = RandomUtil.randomNumbers(6);
        //将验证码保存在redis 设置过期时间2分钟
        redisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //发送验证码
        log.debug("验证码：{}", code);
        //返回ok
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //从redis中获取验证码
        String phone = loginForm.getPhone();
        String cacheCode = redisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        String code = loginForm.getCode();
        //如果校验不通过
        if (Objects.isNull(cacheCode) || !cacheCode.toString().equals(code)) {
            return Result.fail("验证码错误");
        }
        //校验通过,看是否是新用户
        User user = this.query().eq("phone", phone).one();
        //用户没有注册过
        if (Objects.isNull(user)) {
            user = createUserAndSave(phone);
        }
        //保存用户到session ===> 保持userDto[用户基本信息]到session 避免用户名/密码 敏感信息 ===>保持用户到redis
        //1.生成token
        String token = UUID.randomUUID(true).toString();
        //2.token作为key保存用户 hash结构
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> beanToMap = BeanUtil.beanToMap(//由于beanTomap时,userDTO为Long,无法自动转换为String,需要手动设置
                userDTO,new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true).setFieldValueEditor((fieldName,fieldValue)->fieldValue.toString())
                );
        redisTemplate.opsForHash().putAll(LOGIN_USER_KEY+token, beanToMap);
        //3.设置过期时间
        redisTemplate.expire(LOGIN_USER_KEY+token, LOGIN_USER_TTL,TimeUnit.MINUTES);
        //4.返回给客户端token
        return Result.ok(token);
    }

    @Override
    public Result logout(HttpServletRequest request) {
        String token = request.getHeader("authorization");
        log.info("token = "+token);
        redisTemplate.delete(LOGIN_USER_KEY + token);
        return Result.ok();
    }

    @Override
    public Result getUserDtoById(Long id) {
        User user = userMapper.queryById(id);
        if(Objects.isNull(user)){
            return Result.fail("该用户不存在");
        }
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);

        return Result.ok(userDTO);
    }

    @Override
    public Result sign() {
        UserDTO user = UserHolder.getUser();
        Long userId = user.getId();
        //构造Key
        LocalDateTime now = LocalDateTime.now();
        String signPrefix = now.format(DateTimeFormatter.ofPattern(":yyyy:MM"));
        String key = "user:sign:"+userId+signPrefix;
        //签到逻辑
        int dayOfMonth = now.getDayOfMonth();
        redisTemplate.opsForValue().setBit(key,dayOfMonth-1,true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        UserDTO user = UserHolder.getUser();
        Long userId = user.getId();
        //构造Key
        LocalDateTime now = LocalDateTime.now();
        String signPrefix = now.format(DateTimeFormatter.ofPattern(":yyyy:MM"));
        String key = "user:sign:"+userId+signPrefix;
        //获得无符号数 BITFIELD key Get u14 0
        int dayOfMonth = now.getDayOfMonth();
        List<Long> result = redisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType
                        .unsigned(dayOfMonth)).valueAt(0)
        );
        if(Objects.isNull(result) || result.isEmpty()){
            return Result.ok(0);
        }
        Long num = result.get(0);
        if(Objects.isNull(num) || num == 0){
            return Result.ok(0);
        }
        int count = 0;
        while ((num&1)==1){
            count++;
            num>>>=1;
        }
        return Result.ok(count);
    }

    private User createUserAndSave(String phone) {
        //新建用户
        User user = new User();
        user.setPhone(phone).setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        //保存到数据库
        save(user);
        return user;
    }
}
